<template>
  <commonDrawer
   title="导入"
   :drawer="drawer"
   size="40%"
   @closeDraw="openOrCloseDrawer"
   @cancelFun="drawer=false"
   @save="importSaveFun">
   <template slot="column">
          <div class="importTop">
            <div class="clearfix">
              <img :src="uploadImg" class="fl"/>
              <div class="fl" style="margin-left: 20px">
                <p>请下载模板并按照模板格式填写数据后再进行导入，<br>单次带入只读取第一个sheet中的数据。</p>
                <div>
                  <el-button size="mini" class="fl importBtn">
                    <a href="/temp/sip-Import.xlsx" download="批量导入Sip号">下载模板</a>
                  </el-button>
                  <el-upload
                    class="upload-demo"
                    ref="importSip"
                    accept=".xls, .xlsx"
                    :action="importUrl"
                    :limit='1'
                    :on-success="handleImportSuccess"
                    :before-upload="beforeUpload"
                    :on-remove="handleRemove"
                    :headers="{
                      sessionid: $store.state.common.session.user._id,
                      loginToken: $store.state.common.session.user.loginToken
                    }">
                    <el-button type="primary" size="mini" class="fl" style="margin-left: 10px">上传文件</el-button>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
          <div class="content">
            <h5><span class="V7_iconfont V7_iconV7tubiao_zhongyaoxiaoxi"></span>小贴士</h5>
            <ul>
              <li v-for="(item, index) in importTitle" :key="index">{{item}}</li>
            </ul>
          </div>
        </template>
  </commonDrawer>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { IvrModule } from '@/store/modules/config/ivr'
import commonDrawer from '@/common/views/drawer/index.vue'
@Component({
  name: 'ImportSip',
  components: { commonDrawer }
})
export default class ImportSip extends Vue {
  [x: string]: any
  private filepath: string = '' // 上传文件后的地址
  private drawer: boolean = false // 抽屉的控制值
  private uploadImg: any = require('../../../../assets/img/uploadFile.png')
  private importUrl: string = '/upload?accountId=' + this.$store.state.common.session.account._id + '&module=sip'
  private importTitle: any[] = [
    '1.请勿变更表头，*号项为必填项;',
    '2.SIP号：3-6位纯数字；',
    '3.密码：6-18位的数字、大小写字母；',
    '4.是否NAT：是/否（不填写默认为否）；',
    '5.语音编码：G711A/G711U/GSM/G729/ILBC/VP8(不填写默认为G711U)；',
    '6.单次导入上限10000条。'
  ]

  private beforeUpload (file: any) { // 上传前验证文件合法性
    const fileName = /[^.]+$/.exec(file.name.replace(/\s/g, ''))
    if (fileName && (fileName[0] !== 'xls' && fileName[0] !== 'xlsx')) {
      this.$message({ message: '仅支持上传xls,xlsx文件', type: 'error' })
      return false
    }
  }

  private uploadError () { // 上传失败
    this.$message({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
  }

  private handleImportSuccess (res: any) { // 上传成功
    if (res && res.success && res.data) {
      this.filepath = res.data.path
    }
  }

  private openOrCloseDrawer (data: any) { // 打开或者是关闭抽屉 || 父级调用
    this.drawer = !this.drawer
    this.filepath = ''
  }

  private handleRemove () {
    this.filepath = ''
  }

  private importSaveFun () { // SIP号导入保存事件
    if (!this.filepath) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/base/action/transmission/import/task/create',
      method: 'post',
      data: {
        type: 'sip',
        accountId: this.$store.state.common.session.account._id,
        createUser: this.$store.state.common.session.user._id,
        filepath: this.filepath
      }
    }
    const epxortRef: any = this.$refs.importSip
    epxortRef.clearFiles()
    IvrModule.IvrCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        this.filepath = ''
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
        // this.$message.success('导入任务已经生成，请前往传输中心查看！')
        this.drawer = false
      }
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.$router.push('/transmission_center/index/tx_import_task?taskModule=sip')
  }
}
</script>
<style lang="stylus" scoped>
.importTop
  padding 36px
  background $bgc-gray
  p
    color $fc-gray2
    margin-bottom 20px
  .importBtn
    a
      color $fc-gray2
  .importBtn:hover a
    color $c-main
.content
  margin-top 26px
  h5
    font-size 12px
    font-weight 600
  .V7_iconfont
    font-size 14px
    color $c-warn
    margin-right 5px
  li
    color $fc-gray3
    line-height 24px
</style>
